<template>
  <div class="app-container area-content">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="区域名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入区域名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否启用" prop="enabled">
        <el-select v-model="queryParams.enabled" required placeholder="请选择是否启用" clearable>
          <el-option
            v-for="dict in dict.type.self_area_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:area:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:area:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:area:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="areaList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="区域名称" align="left" prop="name" />
      <el-table-column width="150" label="是否启用" align="center" prop="enabled">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.self_area_status" :value="scope.row.enabled"/>
        </template>
      </el-table-column>
      <el-table-column width="150" label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:area:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:area:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改行政区划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入区域名称" />
        </el-form-item>
        <el-form-item label="区域编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入区域编码" />
        </el-form-item>
        <!--<el-form-item label="父级id" prop="parentIds">
          <el-input v-model="form.parentIds" placeholder="请输入父级id列表，不包含自己的id，物化路径，一级使用“/” ，例：/id1/id2/id3/  。 避免查询的时候递归和反递归" />
        </el-form-item>
        <el-form-item label="助记码" prop="helpCode">
          <el-input v-model="form.helpCode" placeholder="请输入助记码,一般为拼音简拼，如昆明市 → kms" />
        </el-form-item>-->
        <el-form-item label="是否启用" prop="enabled">
          <el-radio-group v-model="form.enabled">
            <el-radio
              v-for="dict in dict.type.self_area_status"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="多边形坐标点" prop="polygonPoints">
          <el-input style="display:none" type="textarea" placeholder="请输入内容" />
					<el-link type="warning" @click="eventShowMap">点击设置</el-link>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer
      title="地图标记"
      :visible.sync="mapDrawer"
      direction="rtl"
      size="70%"
      :before-close="handleClose">
      <div class="map" id="map"></div>
      <div class="button-group">
        <div class="btn">
          <el-button @click="eventClearMapPoint">全部清除</el-button>
        </div>
        <div class="btn" style="text-align:center;">
          <el-button type="success" @click="eventConfirmMarker">查看选区</el-button>
        </div>
        <div class="btn">
          <el-button type="primary" :disabled="markers.length < 3" @click="eventSaveMapPoint">确认保存</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { listArea, getArea, delArea, addArea, updateArea } from "@/api/system/area"
import { lazyTMapApiLoaderInstance } from "@/utils/TMapInit"

var markers = [];
export default {
  name: "Area",
  dicts: ['self_area_status'],
  data() {
    return {
      maploading:false,
      center :{ lat: 39.91799, lng: 116.397027 },
      // 地图选择层
      mapDrawer:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 行政区划表格数据
      areaList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        enabled: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
				name: [
					{ required: true, message: '请输入地区名称', trigger: 'blur' }
				],
				enabled: [
					{ required: true, message: '请选择开启状态', trigger: 'change' }
				],
				polygonPoints:[
					{ required: true, message: '请选择区域范围', trigger: 'change' }
				]
      },
      map:null,
      marker:null,
			polygon:null,
			markers:[]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    mapInited(){
    	this.maploading = true;
			this.initMap();
    },
		/** 生成选区 */
		eventConfirmMarker(){
			var that = this;
			if(this.markers.length>2){
				that.polygon.add({
					id:"choosePolygon",
					paths:this.markers
				});
			}else{
				this.$modal.msgError("左边点不足")
			}
		},
    /** 刷新地图信息*/
    reflushMap(center){
			var that = this;
			//清除marker等数据
			//开始操作
			if(this.map){
				this.map.setCenter(center);
			}else{
				this.map = new TMap.Map("map", {
					zoom: 17, // 设置地图缩放
					center: center, // 设置地图中心点坐标，
					pitch: 0, // 俯仰度
					rotation: 0, // 旋转角度
				});

				//生成事件
				this.map.on("click",function(e){
					console.log("markers",that.markers);
					that.marker.add({
						position: e.latLng,
						id:"marker-"+that.markers.length
					})
					that.markers.push(e.latLng);
				})
			}
			//如果form中有数据则直接生成markers
			let points = this.form.polygonPoints;
			try{
				points = JSON.parse(points);
				points = points ? points : [];
			}catch(e){
				points = [];
			}
			console.log("points",points);

			if(!this.marker){
				this.marker = new TMap.MultiMarker({
					map: this.map,
					id:"marker-map"
				});
			}
			if(!this.polygon){
				this.polygon = new TMap.MultiPolygon({
					id: 'polygon-layer', // 图层id
					map: this.map, // 显示多边形图层的底图
					styles: {
						// 多边形的相关样式
						polygon: new TMap.PolygonStyle({
							color: '#3777FF', // 面填充色
							showBorder: false, // 是否显示拔起面的边线
							borderColor: '#00FFFF', // 边线颜色
						}),
					},
					geometries: [],
				});
			}

			if(points.length){
				//生成到markers中
				for(var n in points){
					let p = new TMap.LatLng(points[n][1], points[n][0]);
					this.marker.add({
						position: p,
						id:"marker-"+that.markers.length
					})
					this.markers.push(p);
				}
				this.eventConfirmMarker();
			}
		},
    /** 保存地图点位信息*/
		eventSaveMapPoint(){
			let arr = [];
			for(var n in this.markers){
				arr.push([this.markers[n].lng,this.markers[n].lat]);
			}
			this.form.polygonPoints = JSON.stringify(arr);
			this.handleClose();
		},
    /** 保存地图点位信息*/
		eventClearMapPoint(){
			this.polygon.remove("choosePolygon");
			for(var n in this.markers){
				this.marker.remove("marker-"+n);
			}
			this.markers = [];
		},
    /** 关闭地图选择器*/
		handleClose(){
			try{
				this.mapDrawer = false;
				this.map.destroy();
				this.map = null;
				this.marker = null;
				this.polygon = null;
				this.markers = [];
			}catch(e){}
			console.log("关闭地图选择器");
		},
		/** 显示地图选择器*/
		eventShowMap() {
			this.mapDrawer = true;
			lazyTMapApiLoaderInstance.then(() => {
				var geocoder = new TMap.service.Geocoder();
				console.log(this.form.name);
				geocoder.getLocation({ address:this.form.name}).then((res) => {
					console.log("解析地址：",res);
					//初始化地图
					this.reflushMap(res.result.location);
				}).catch((res) => {
					console.log("解析错误",res);
					this.$modal.msgError("无法检测到城市名称，请输入正确的城市名称")
					this.mapDrawer = false;
				});
			})
    },
    /** 查询行政区划列表 */
    getList() {
      this.loading = true
      listArea(this.queryParams).then(response => {
        this.areaList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createTime: null,
        updateTime: null,
        name: null,
        code: null,
        parentId: null,
        parentIds: null,
        helpCode: null,
        enabled: null,
        polygonPoints: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加行政区划"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getArea(id).then(response => {
				response.data.polygonPoints = response.data.polygonPoints ? JSON.stringify(response.data.polygonPoints) : "";
        this.form = response.data
        this.open = true
        this.title = "修改行政区划"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
					let params = this.form;
					params.polygonPoints = this.form.polygonPoints ? JSON.parse(this.form.polygonPoints) : [];
          if (this.form.id != null) {
            updateArea(params).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addArea(params).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认编号为"' + ids + '"的数据项？').then(function() {
        return delArea(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/area/export', {
        ...this.queryParams
      }, `area_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style lang="scss">
	.area-content{
		.map{
			height:83vh;
		}
		.button-group{
			padding:0px 25px;
			height:80px;
			line-height:80px;
			display:flex;
			.btn{
				flex:1;
				align-items:center;
				&:last-child{
					text-align:right;

				}
			}
		}
	}
</style>